﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;



namespace logwiz
{
    

    public partial class Form1 : Form
    {
        string sCompName; // to store the name of the local computer 
        string sTrgtCompName; //to run the perfmon log on. Incase the user is trying to run the logs remotely. Need to compare the name later.
        int sz; // total number of perf counters on the server 
        string[] chkboxname = new string[500];
        string cmd1, cmd2, cmd3, cmd5; // variable to set the logman command
        //cmd3 is for advanced. cmd5 is for general
        string cmd4;  // the string to start the perfmon that we just created.
        Process myProcess = new Process(); // instance of the process object
        string cd,ab; // temp strings get the date and time of the machine
        static string tn; // for storing the name of the data collector set
        int a, b, c, d; // temp variables for calculation of snapshots
        int snapshotinterval = 7; //the variables storing the value of number of snapshots in secnds
        int setintrvl;// temp variable for setting up the time interval in override mode
        decimal de; // temp vairalbe to deciding the number of snapshots after rounding off
        string button_pressed; // for checking if the button was pressed or not. so tht next can be enabled.
        string msgpop; // for checking if we selected any counters or not in the advanced mode
        //public string[] RemoveDuplicates(string[] myList)
        //{
        //    System.Collections.ArrayList newList = new System.Collections.ArrayList();
        //    foreach (string str in myList)
        //        if (!newList.Contains(str))
        //            newList.Add(str);
        //    return (string[])newList.ToArray(typeof(string));
        //}

        public void overrideinterval() // if the interval is overridden
        {
            if ((checkBox2.Checked == true) && (textBox7.Text != ""))
            {

                switch (comboBox2.SelectedItem.ToString())
                {
                    case "Seconds": a = Convert.ToInt32(textBox7.Text.ToString());
                        setintrvl = a;
                        break;
                    case "Minutes": a = Convert.ToInt32(textBox7.Text.ToString());
                        setintrvl = a * 60;
                        break;

                    case "Hours": a = Convert.ToInt32(textBox7.Text.ToString());
                        setintrvl = a * 3600;
                        break;

                    case "Days": a = Convert.ToInt32(textBox7.Text.ToString());
                        setintrvl = a * 24 * 3600;
                        break;

                }

                snapshotinterval = setintrvl;

            } // close if 

        }

         public void makename() // for creating the name of the logfile.
        {
           // cd = DateTime.Now.ToShortTimeString();
            cd = DateTime.Now.ToLongTimeString();
            ab = DateTime.Now.ToShortDateString();
            cd = ab +"_" + cd;

             cd = cd.Replace(" ", "_");
            cd = cd.Replace("/", "_");
            cd = cd.Replace("\\", "_");
            cd = cd.Replace("-", "_");
            cd = cd.Replace(":", "_");

           // int s = cd.Length;
           // if (s>8)//change the size of the string if its more than 7. if less then leave it as it is.
            //cd = cd.Remove(15); 
            tn = "logwiz" + "-" + cd;
        }

         public void showcmd() // for showing the command in the text box
         {
             if ((radioButton1.Checked == true) || (radioButton5.Checked == true) || (radioButton4.Checked == true) || (radioButton3.Checked == true))
             {
                 textBox8.Text = "logman.exe " + cmd5;  // for the generall method
                 cmd4 = "start " + tn;  
                 textBox8.Text = textBox8.Text + "\r\n" + cmd4; // putting everything in the textbox
             
             }

             else
             {
                 textBox8.Text = "logman.exe " + cmd3; // for the advanced method
                 textBox8.Text = textBox8.Text + "\r\n" + cmd4; // putting everything in the textbox
             }

         }

        public void addcounters()  // for adding the counters dynamically to the form once we load it.

        {
            int topPosition = 10;
            PerformanceCounterCategory[] perfCounters = PerformanceCounterCategory.GetCategories();
            sz = perfCounters.Length;
            string[] perfcountername = new string[sz];
            string[] chkboxname = new string[sz];
            string[] unique = new string[sz];
            for (int i = 0; i < perfCounters.Length; i++)
            {
                perfcountername[i] = perfCounters[i].CategoryName.ToString();
            }
            int j = 0;
            Array.Sort(perfcountername);  // to sort the counters in  accending order
            
           foreach (string pc in perfcountername)
            {
                CheckBox checkBox = new CheckBox();
                checkBox.Top = topPosition;
                checkBox.Left = 10;
                checkBox.Text = pc;
                checkBox.Width = 170;
               //checkBox1.to
                //checkBox.AutoSize = true;

                topPosition += 10;
                checkBox.Name = chkboxname[j];
                flowLayoutPanel1.Controls.Add(checkBox);
                j++;
            }
        }//end of add counters

        public void createcmd() // for creating the logman command in advanced mode
        {
            makename();
            listBox1.Items.Clear();
            cmd1 = cmd2 = null;
            foreach (Control c in flowLayoutPanel1.Controls)
            {
                if (c is CheckBox)
                {
                    CheckState x = ((CheckBox)c).CheckState; // Do whatever you want to do with CheckedState ( Value Of Check box )
                    if (((CheckBox)c).Checked == true)
                    {
                        listBox1.Items.Add(c.Text);
                        cmd1 = "\"\\"+ c.Text +"(*)\\*\" ";
                        cmd2 = cmd2 + cmd1;
                                   
                    }
                }

            }

            if ((listBox1.Items.Count.Equals(0)) && ((radioButton2.Checked == true)))
            {
                MessageBox.Show("You have not selected any objects to add. Please go back and select some objects to monitor", "No objects selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
                button7.Enabled = true;
                button_pressed = "No";
                button1.Enabled = false;
                msgpop = "Yes";
            }
            else
            {

                // for unique names 
                cmd3 = "create counter " + tn + " -o \"" + textBox5.Text + "\\logwiz\" -c " + cmd2 + " -f bincirc -max " + textBox4.Text + " -si " + snapshotinterval.ToString() + " -v mmddhhmm -ow";
                cmd4 = "start " + tn;
            }

       }

        public void starttheprocess()
        {
             
            if (msgpop == "No")  // start the process only if there was no error/
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;//Turn on the hourglass cursor here.
                    myProcess.StartInfo.ErrorDialog = true;
                    myProcess.StartInfo.UseShellExecute = true;
                    myProcess.StartInfo.CreateNoWindow = true;
                    myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    myProcess.Start();
                    myProcess.WaitForExit();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }

                //Turn off the hourglass cursor here.
                this.Cursor = Cursors.Default;

            }

                    
        } //end of the start process function

        public void settheinterval()  // for getting the number of snapshots 
        {

            // assuming a is in seconds which is the value initially in the text box6

            if (textBox6.Text == "")
                textBox6.Text = "1";

            switch (comboBox1.SelectedItem.ToString())
            {
                case "Minutes": a = Convert.ToInt32(textBox6.Text.ToString());
                    b = a * 60;
                    break;

                case "Hours": a = Convert.ToInt32(textBox6.Text.ToString());
                    b = a * 3600;
                    break;

                case "Days": a = Convert.ToInt32(textBox6.Text.ToString());
                    b = a * 24 * 3600;
                    break;

            }

           // textBox3.Text = b.ToString();

            //b has my value in seconds.

            //diving it by 480 to get the snapshots
            de = b / 480;
            c = Convert.ToInt32(Math.Round(de));
            snapshotinterval = c; // for safeguard copying the values
            //  d is my sample interval in seconds.
            if (c < 1)
                c = 1;
            
            if (c < 60) // for seconds
            {
                textBox7.Text = c.ToString();
                comboBox2.SelectedIndex = 0;
            }

            else
            {
                if ((c >= 60) && (c < 3600))  // for minutes
                {
                    c = c / 60;
                    textBox7.Text = c.ToString();
                    comboBox2.SelectedIndex = 1;
                }

                else
                {
                    if ((c >= 3600) && (c < 84600)) // hours
                    {
                        c = c / 60;

                        textBox7.Text = c.ToString();
                        comboBox2.SelectedIndex = 2;
                    }

                    else
                    {
                        if ((c >= 84600)) // for days
                        {
                            c = (c / (60 * 24));
                            textBox7.Text = c.ToString();
                            comboBox2.SelectedIndex = 3;
                        }
                    }

                }

            }
            // textBox4.Text = c.ToString();

        } // close of function 


        public Form1()
        {
            InitializeComponent();
            PerformanceCounterCategory[] perfCounters = PerformanceCounterCategory.GetCategories();
            button_pressed = "No";
            msgpop = "No";
        }

        private void button1_Click(object sender, EventArgs e)
        {
                     
            
            if (tabControl1.SelectedTab.Name.Equals("tabPage8"))
                button1.Enabled = false;
            else  button1.Enabled = true;

            if (button_pressed == "Yes")
            {
                button1.Enabled = true;
                //button7.Enabled = false;
            }
                      
            
            int a = tabControl1.SelectedIndex;
            a++;
            tabControl1.SelectedIndex = a;

            

            button2.Enabled = true;

            if ((a==3)&&(radioButton1.Checked == true))  // general selected
                tabControl1.SelectTab(6);
            else if ((a == 3) && (radioButton3.Checked == true)) // high cpu selected
                tabControl1.SelectTab(6);
            else if ((a == 3) && (radioButton5.Checked == true)) // network selected
                tabControl1.SelectTab(6);
            else if ((a == 3) && (radioButton4.Checked == true)) // RDP selected
                tabControl1.SelectTab(6);


        }

        private void button2_Click(object sender, EventArgs e)
        {
            if ((tabControl1.SelectedTab.Name.Equals("tabPage7")) && ((radioButton1.Checked == true) || (radioButton5.Checked == true) || (radioButton4.Checked == true) || (radioButton3.Checked == true)))
                tabControl1.SelectTab(2);
            else
            {
                int a = tabControl1.SelectedIndex;
                a--;
                tabControl1.SelectedIndex = a;
                if (tabControl1.SelectedTab.Name.Equals("tabPage1"))
                    button2.Enabled = false;
                else
                    button2.Enabled = true;
                button_pressed = "No";
            }

            

            button1.Enabled = true;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = System.Environment.MachineName.ToString();
            sCompName = textBox1.Text;
            textBox2.Text = System.Environment.MachineName.ToString();
            sTrgtCompName = textBox2.Text;
            addcounters();

        }

        private void button4_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            textBox5.Text = folderBrowserDialog1.SelectedPath;

        }

      
        private void button7_Click(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
            myProcess.StartInfo = new ProcessStartInfo(@"logman.exe", cmd5); // for general

            else if (radioButton3.Checked == true)
                myProcess.StartInfo = new ProcessStartInfo(@"logman.exe", cmd5); // for high cpu
            else if (radioButton5.Checked == true)
                myProcess.StartInfo = new ProcessStartInfo(@"logman.exe", cmd5); // for network

            else if (radioButton4.Checked == true)
                myProcess.StartInfo = new ProcessStartInfo(@"logman.exe", cmd5); // for RDP

            else if (radioButton2.Checked == true)
            {
              createcmd();
              myProcess.StartInfo = new ProcessStartInfo(@"logman.exe", cmd3); // for advanced
            }
            showcmd();
            starttheprocess();  // starting the perfmon logs - 

            // System.Diagnostics.Process.Start(@"logman", cmd3);
            //if (tabControl1.SelectedTab.Equals("tabPage7"));
            if (msgpop == "No") // do not enable the buttons after running the command.
            {
                button7.Enabled = false;
                button1.Enabled = true;
                button_pressed = "Yes";
            }
            msgpop = "No";

        }

        private void button3_Click(object sender, EventArgs e)
        {
            
            myProcess.StartInfo = new ProcessStartInfo(@"logman.exe", cmd4);
            starttheprocess();
            //System.Diagnostics.Process.Start(@"logman", cmd4);
            Application.Exit();
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            
           if (radioButton1.Checked == true) // for general logging
            {   makename();
            cmd5 = "create counter " + tn + " -c  \"\\Cache\\*\" \"\\LogicalDisk(*)\\*\" \"\\Network Interface(*)\\*\" \"\\Processor(*)\\*\" \"\\Memory\\*\" \"\\Paging File(*)\\*\" \"\\PhysicalDisk(*)\\*\" \"\\Server\\*\" \"\\Process(*)\\*\" \"\\System\\*\"  \"\\Objects\\*\" \"\\Redirector\\*\"  -f bincirc -max 500 -si 00:00:15  -v mmddhhmm -ow";
             }
            button7.Enabled = true;

        }

        private void tabPage7_Enter(object sender, EventArgs e)
        {
            if (button_pressed != "Yes")
                button1.Enabled = false;

         else if (radioButton2.Checked == true)
                button1.Enabled = false;
                //else  button1.Enabled = true;

            //if ((listBox1.Items.Count.Equals(0))&& ((radioButton2.Checked == true)))
            //MessageBox.Show("You have not selected any objects to add. Please go back and select some objects to monitor", "No objects selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
               
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            button7.Enabled = true;
        }

        private void tabPage6_Enter(object sender, EventArgs e)
        {
       //     button7.Enabled = true;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
           // if (checkBox2.Checked == true)
            showcmd(); // for populating the textbox with the commmand
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            settheinterval();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            settheinterval();
        }

        private void textBox6_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 127 || e.KeyChar == 8 || e.KeyChar == 13)
            {
                e.Handled = false;
            }
            else
            {
                //MessageBox.Show("Invalid Input");
                e.Handled = true;
            } 
        }

      

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {

            if (radioButton3.Checked == true) // for high cpu logging
            {
                makename();
                cmd5 = "create counter " + tn + " -c  \"\\Cache\\*\" \"\\LogicalDisk(*)\\*\" \"\\Network Interface(*)\\*\" \"\\Processor(*)\\*\" \"\\Memory\\*\" \"\\Paging File(*)\\*\" \"\\PhysicalDisk(*)\\*\" \"\\Server\\*\" \"\\Process(*)\\*\" \"\\System\\*\" \"\\Threads\\*\" \"\\Objects\\*\" \"\\Redirector\\*\"  -f bincirc -max 500 -si 00:00:15  -v mmddhhmm -ow";
            }
            button7.Enabled = true;
        }

        private void radioButton5_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton5.Checked == true) // for Network related logging
            {
                makename();
                cmd5 = "create counter " + tn + " -c  \"\\Cache\\*\" \"\\LogicalDisk(*)\\*\" \"\\Network Interface(*)\\*\" \"\\Processor(*)\\*\" \"\\Memory\\*\" \"\\Paging File(*)\\*\" \"\\PhysicalDisk(*)\\*\" \"\\Server\\*\" \"\\Process(*)\\*\" \"\\System\\*\" \"\\Objects\\*\" \"\\Redirector\\*\" \"\\ICMP\\*\" \"\\ICMPv6\\*\" \"\\IPv4\\*\" \"\\IPv6\\*\" \"\\TCPv4\\*\" \"\\TCPv6\\*\" \"\\UDPv4\\*\" \"\\UDPv6\\*\" \"\\Per Processor Network Interface Card Activity\\*\"  -f bincirc -max 500 -si 00:00:15  -v mmddhhmm -ow";
            }
            button7.Enabled = true;
        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton4.Checked == true) // for RDP logging
            {
                makename();
                cmd5 = "create counter " + tn + " -c  \"\\Cache\\*\" \"\\LogicalDisk(*)\\*\" \"\\Network Interface(*)\\*\" \"\\Processor(*)\\*\" \"\\Memory\\*\" \"\\Paging File(*)\\*\" \"\\PhysicalDisk(*)\\*\" \"\\Server\\*\" \"\\Process(*)\\*\" \"\\System\\*\" \"\\Objects\\*\" \"\\Redirector\\*\" \"\\Terminal Services\\*\" \"\\Terminal Services Session\\*\" -f bincirc -max 500 -si 00:00:15  -v mmddhhmm -ow";
            }
            button7.Enabled = true;
        }

        private void checkBox2_CheckedChanged_1(object sender, EventArgs e)
        {
            if (checkBox2.Checked == true)
               textBox7.Enabled = true;
            else
                textBox7.Enabled = false;


        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            overrideinterval();

           
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            overrideinterval();
        }

        private void textBox7_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 127 || e.KeyChar == 8 || e.KeyChar == 13)
            {
                e.Handled = false;
            }
            else
            {
                //MessageBox.Show("Invalid Input");
                e.Handled = true;
            } 
        }

        private void tabPage8_Enter(object sender, EventArgs e)
        {
            button1.Enabled = false;
        }

     


             

           
    }
}
